from flask_restful import marshal_with, Resource
from flask_jwt_extended import jwt_required
from flask_restful_swagger import swagger
from .resources import UserResource
from .models import User


class AuthLoginView(Resource):
    def post(self):
        args = UserResource.validate_login()
        user = User.query.filter_by(username=args.username).first()
        if user and user.verify(args.password):
            return user.token, 200
        return '', 400


class UsersView(Resource):
    @marshal_with(UserResource.fields)
    def post(self):
        args = UserResource.validate_create()
        user = User(username=args.username)
        user.set_password(password=args.password)
        user.create()
        return user

    @marshal_with(UserResource.fields)
    @jwt_required
    def get(self):
        return User.query.all()
